package top.littlejiang.onlinexam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.littlejiang.onlinexam.common.base.BasePage;
import top.littlejiang.onlinexam.common.base.BaseServiceImpl;
import top.littlejiang.onlinexam.common.base.BusinessException;
import top.littlejiang.onlinexam.common.base.LoginException;
import top.littlejiang.onlinexam.common.utils.DateUtils;
import top.littlejiang.onlinexam.common.utils.JWTUtils;
import top.littlejiang.onlinexam.common.utils.PasswordUtils;
import top.littlejiang.onlinexam.entity.OlexamUser;
import top.littlejiang.onlinexam.mapper.OlexamUserMapper;
import top.littlejiang.onlinexam.service.OlexamUserService;
import top.littlejiang.onlinexam.vo.ModifyInformationVO;

import java.io.Serializable;
import java.util.List;


/**
 * <p>
 * OlexamUser 服务实现类
 * </p>
 *
 * @author chen
 * @since 2020-12-26
 */
@Service
public class OlexamUserServiceImpl extends BaseServiceImpl<OlexamUserMapper, OlexamUser> implements OlexamUserService {

    @Autowired
    private OlexamUserMapper userMapper;

    /**
     * 根据id查询用户
     * 包含用户角色
     * @param userId
     * @return
     */
    @Override
    public OlexamUser getUserById(int userId) {
        return userMapper.getUserById(userId);
    }

    /**
     * 根据账号查用户（登录使用）
     *
     * @param userAccount
     * @return
     */
    @Override
    public OlexamUser getUserByAcct(String reqService, int userAccount) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id,user_name,user_salty,user_pwd");
        wrapper.eq("user_account",userAccount);
        wrapper.eq("is_del",0);
        OlexamUser olexamUser = this.selectOne(wrapper);
        if (olexamUser == null && reqService.equals(OlexamLoginServiceImpl.LOGIN_SERVICE)){
            throw new LoginException("用户不存在");
        }
        return olexamUser;
    }

    /**
     * 更新个人信息
     *
     * @param vo
     */
    @Override
    public void modifyOne(ModifyInformationVO vo) {
        String userSalty = PasswordUtils.getRandomValue(PasswordUtils.DEFAULT_LENGTH);
        String userPwd = PasswordUtils.md5SaltyAndPwd(userSalty, vo.getUserPwd());

        UpdateWrapper<OlexamUser> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", JWTUtils.getUserId())
                .set("user_phone", vo.getUserPhone())
                .set("user_email", vo.getUserEmail())
                .set("user_salty", userSalty)
                .set("user_pwd", userPwd)
                .set("update_time", DateUtils.getTime());
        update(wrapper);
    }

    /**
     * 分页查询用户列表
     *
     * @param userPage
     * @return
     */
    @Override
    public IPage<OlexamUser> getUserListPage(BasePage<OlexamUser> userPage) {
        OlexamUser param = userPage.getQueryParam();
        QueryWrapper<OlexamUser> wrapper = new QueryWrapper<>();
        if (!StringUtils.isBlank(param.getUserName())){
            wrapper.like("user_name", param.getUserName());
        }
        if (userPage.getPageSize() <= 0){
            userPage.setPageSize(10);
        }
        Page<OlexamUser> p = new Page<>(userPage.getPageIndex(), userPage.getPageSize());
        IPage<OlexamUser> list = userMapper.getUserList(p, wrapper);
        return list;
    }

   /**
    * 根据姓名检查用户是否有效
    * @param userName
    * @param userPhone
    * @return Integer
    * @author chen
    * @since 2021/3/12 13:32
    */
    @Override
    public Integer checkByName(String userName, String userPhone) {
        if (StringUtils.isBlank(userName)){
            throw new BusinessException("用户名不能为空");
        }
        QueryWrapper<OlexamUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName)
                .eq("is_del", 0);
        if (StringUtils.isNoneBlank(userPhone)){
            wrapper.eq("user_phone", userPhone);
        }
        List<OlexamUser> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)){
            throw new BusinessException("无法找不到对应用户信息");
        }
        if (list.size() == 1){
            return list.get(0).getId();
        } else {
            throw new BusinessException("此用户信息包含多个用户，请确认联系方式再次输入");
        }

    }

    /**
     * 根据姓名模糊查询 返回id，phone，name
     *
     * @param userName
     * @return
     */
    @Override
    public List<OlexamUser> getUserSelect(String userName) {
        if (StringUtils.isBlank(userName)){
            throw new BusinessException("请输入待查询用户名");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id,user_name,user_phone");
        wrapper.like("user_name", userName);
        wrapper.eq("is_del", 0);
        return this.list(wrapper);
    }

    /**
     * 根据班级id 获取用户id
     *
     * @param fkClassId
     * @return
     */
    @Override
    public List<Serializable> getUserIdByClass(Integer fkClassId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.select("id");
        wrapper.eq("fk_class_id", fkClassId);
        wrapper.eq("is_del", 0);
        List<Serializable> list = listObjs(wrapper);
        return list;
    }


}
